package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zzyl.common.utils.CodeGenerator;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.dto.CheckInConfigDto;
import com.zzyl.nursing.dto.CheckInContractDto;
import com.zzyl.nursing.dto.CheckInElderDto;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;

/**
 * 入住Service业务层处理
 * 
 * @author zzyl
 * @date 2025-10-16
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService
{
    @Autowired
    private CheckInMapper checkInMapper;

    @Autowired
    private ElderMapper elderMapper;

    @Autowired
    private BedMapper bedMapper;

    @Autowired
    private CheckInConfigMapper checkInConfigMapper;

    @Autowired
    private ContractMapper contractMapper;

    /**
     * 查询入住
     * 
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询入住列表
     * 
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn)
    {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn)
    {
        return save(checkIn) ? 1 : 0;
    }

    /**
     * 修改入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn)
    {
        return updateById(checkIn) ? 1 : 0;
    }

    /**
     * 批量删除入住
     * 
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除入住信息
     * 
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }

    @Transactional
    @Override
    public void apply(CheckInApplyDto dto) {
        Elder elder = elderMapper.selectOne(Wrappers.<Elder>lambdaQuery()
                .eq(Elder::getIdCardNo, dto.getCheckInElderDto().getIdCardNo())
                .eq(Elder::getStatus, 1)
        );
        Bed bed = bedMapper.selectBedById(dto.getCheckInConfigDto().getBedId());
        String bedNumber = bed.getBedNumber();
        if (bed.getBedStatus() == 0){
            bed.setBedStatus(1);
        }else {
            throw new RuntimeException("该床位已入住");
        }


        if (ObjectUtils.isNotEmpty( elder)){
            throw new RuntimeException("该老人已入住");
        }
         elder = saveElderInfo(dto, bedNumber);

        saveContract(dto,elder);

        Long checkInId = saveCheckIn(dto, elder, bedNumber);

        saveCheckInConfig(dto,checkInId);

    }


    private Elder saveElderInfo(CheckInApplyDto dto ,String bedNumber) {
        CheckInElderDto checkInElderDto = dto.getCheckInElderDto();
        Elder elder = elderMapper.selectOne(Wrappers.<Elder>lambdaQuery()
                .eq(Elder::getIdCardNo, checkInElderDto.getIdCardNo())
                .eq(Elder::getStatus, 0)
        );
            Elder newElder = BeanUtil.toBean(checkInElderDto, Elder.class);
            newElder.setStatus(1);
            newElder.setBedId(dto.getCheckInConfigDto().getBedId());
            newElder.setBedNumber(bedNumber);
        if (ObjectUtils.isEmpty(elder)){
            elderMapper.insert(newElder);
        }else {
            elderMapper.updateById(newElder);
        }

        return newElder;
    }


    private void saveContract(CheckInApplyDto dto, Elder elder) {
        CheckInContractDto checkInContractDto = dto.getCheckInContractDto();
        Contract contract = BeanUtil.toBean(checkInContractDto, Contract.class);
        contract.setElderId(Math.toIntExact(elder.getId()));
        contract.setElderName(elder.getName());
        contract.setStartDate(dto.getCheckInConfigDto().getStartDate());
        contract.setEndDate(dto.getCheckInConfigDto().getEndDate());
        contract.setContractNumber(CodeGenerator.generateContractNumber());
        contract.setStatus(contract.getStartDate().isBefore(LocalDateTime.now())? 0:1 );
        contractMapper.insert(contract);
    }

    private Long saveCheckIn(CheckInApplyDto dto,Elder elder,String bedNumber) {
        CheckInConfigDto checkInConfigDto = dto.getCheckInConfigDto();

        CheckIn checkIn = BeanUtil.toBean(checkInConfigDto, CheckIn.class);
        checkIn.setElderId(elder.getId());
        checkIn.setElderName(elder.getName());
        checkIn.setIdCardNo(elder.getIdCardNo());
        checkIn.setBedNumber(bedNumber);
        checkIn.setRemark(JSON.toJSONString(dto.getElderFamilyDtoList()));
        checkIn.setStatus(0);
        checkInMapper.insert(checkIn);
        return checkIn.getId();
    }

    private void saveCheckInConfig(CheckInApplyDto dto, Long checkInId) {
        CheckInConfigDto checkInConfigDto = dto.getCheckInConfigDto();
        CheckInConfig checkInConfig = BeanUtil.toBean(checkInConfigDto, CheckInConfig.class);
        BeanUtils.copyProperties(dto.getCheckInConfigDto(), checkInConfig);
        checkInConfig.setCheckInId(checkInId);
        checkInConfigMapper.insert(checkInConfig);
    }



    @Override
    public CheckInDetailVo detail(Integer id) {
        CheckIn checkIn = this.getById(id);

        CheckInDetailVo result = new CheckInDetailVo();
        CheckInElderVo checkInElderVo = checkInMapper.getByCheckId(id);
        List<ElderFamilyVo> elderFamilyVoList = JSON.parseArray(checkIn.getRemark(), ElderFamilyVo.class);
        CheckInConfigVo checkInConfigVo = checkInConfigMapper.getByCheckId(id);
        Contract contract = contractMapper.getByElderId(checkInElderVo.getId());

        result.setCheckInConfigVo(checkInConfigVo);
        result.setCheckInElderVo(checkInElderVo);
        result.setElderFamilyVoList(elderFamilyVoList);
        result.setContract(contract);
        return result;
    }

}
